package cn.itcast.web.servlet; /**
 * @author skycat
 * @time 2021/12/9
 */

import cn.itcast.pojo.AdminUser;
import cn.itcast.service.UserService;
import cn.itcast.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //先进行验证码的校验，减轻服务器压力
        String verifycode = request.getParameter("verifycode");
        HttpSession session = request.getSession();
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
        session.removeAttribute("CHECKCODE_SERVER");
        if(!checkcode_server.equalsIgnoreCase(verifycode)){
            //验证码错误
            //提示错误信息
            request.setAttribute("login_msg","验证码填写错误!");
            request.getRequestDispatcher("/login.jsp").forward(request,response);

            return;

        }
        Map<String, String[]> map = request.getParameterMap();
        AdminUser user=new AdminUser();
        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //调用service方法查询
        UserService userService=new UserServiceImpl();
        AdminUser loginUser = userService.findAdminUser(user);
        if(loginUser!=null){
            //登录成功
            session.setAttribute("adminUser",user);
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }else{
            //登录失败，用户名或密码错误!
            request.setAttribute("login_msg","用户名或密码错误!");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doGet(request,response);
    }
}
